<template>
  <ElementDialog ref="dialog" :visible="visible" embed title="移动文件" width="400px">
    <template #default>
      <div style="height: 400px; overflow: auto">
        <ElTree ref="tree" lazy :expand-on-click-node="false" :load="load" />
      </div>
    </template>
    <template #footer>
      <ElButton size="mini" @click="() => $refs.dialog.hide()">取 消</ElButton>
      <ElButton size="mini" type="primary" @click="confirm">确 定</ElButton>
    </template>
  </ElementDialog>
</template>

<script>
  import { copyFiles, moveFiles } from '@/api/file'

  export default {
    name: 'CopyOrMoveDialog',
    props: {
      visible: Boolean,
      api: Function,
      files: Array,
      action: String
    },
    methods: {
      async load(node, resolve) {
        const res = await this.api(node.level === 0 ? null : node.data.id, node)
        res.data.data.forEach(value => {
          value.name = value.filename
          value.label = value.filename
        })
        resolve(res.data.data)
      },
      async confirm() {
        const target = this.$refs.tree.getCurrentNode()
        if (this.action === 'move') {
          await moveFiles({
            fileIds: this.files.map(value => value.id),
            directoryId: target.id
          })
        }
        if (this.action === 'copy') {
          await copyFiles({
            fileIds: this.files.map(value => value.id),
            directoryId: target.id
          })
        }
        this.$emit('success')
      }
    }
  }
</script>
